package com.thuanpq60023.easyenglish.adapter;

import com.thuanpq60023.easyenglish.entity.UnitEntity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

public class UnitAdapter {
	private DatabaseAdapter mDbAdapter;

	public UnitAdapter(Context context) {
		mDbAdapter = new DatabaseAdapter(context);
	}

	public boolean insertUnit(UnitEntity entity) {
		if (entity != null) {
			ContentValues inititalValues = new ContentValues();
			inititalValues.put(UnitEntity.NAME, entity.getName());
			inititalValues.put(UnitEntity.CREATEDDATE, entity.getCreatedDate());

			boolean result = mDbAdapter.insert(UnitEntity.TABLE_NAME, null,
					inititalValues) > 0;
			return result;
		}
		return false;
	}

	public boolean deleteUnitByName(String name) {
		return mDbAdapter.delete(UnitEntity.TABLE_NAME, UnitEntity.NAME + "=?",
				new String[] { name }) > 0;
	}

	public boolean updateUnitByName(UnitEntity entity) {
		if (entity != null) {
			ContentValues inititalValues = new ContentValues();

			inititalValues.put(UnitEntity.NAME, entity.getName());
			inititalValues.put(UnitEntity.CREATEDDATE, entity.getCreatedDate());

			boolean result = mDbAdapter.update(UnitEntity.TABLE_NAME,
					inititalValues, UnitEntity.NAME + "=?",
					new String[] { entity.getName() }) > 0;

			return result;
		}
		return false;
	}

	public UnitEntity[] getAllUnit() {

		UnitEntity[] units = null;
		Cursor cur = mDbAdapter.query(UnitEntity.TABLE_NAME, null, null, null,
				null, null, null);
		if (cur != null) {
			units = new UnitEntity[cur.getCount()];
			int i = 0;
			while (!cur.isAfterLast()) {
				units[i++] = getUnitEntity(cur);
				cur.moveToNext();
			}
			cur.close();
		}
		return units;
	}

	public String[] getAllUnitName() {
		String[] units = null;
		int i = 0;
		Cursor cur = mDbAdapter.query(UnitEntity.TABLE_NAME, null, null, null,
				null, null, null);
		if (cur != null) {
			units = new String[cur.getCount()];
			while (!cur.isAfterLast()) {
				units[i++] = getUnitEntity(cur).getName();
				cur.moveToNext();
			}
			cur.close();
		}
		return units;
	}

	public UnitEntity getUnitByName(String name) {
		UnitEntity unit = null;
		Cursor cur = mDbAdapter.query(UnitEntity.TABLE_NAME, null,
				UnitEntity.NAME + " = ? ", new String[] { name }, null, null,
				null);
		if (cur != null) {
			while (!cur.isAfterLast()) {
				unit = getUnitEntity(cur);
				cur.moveToNext();
			}
			cur.close();
		}
		return unit;
	}

	private UnitEntity getUnitEntity(Cursor cur) {
		if (cur != null) {
			UnitEntity values = new UnitEntity();

			values.setName(cur.getString(cur.getColumnIndex(UnitEntity.NAME)));
			values.setCreatedDate(cur.getString(cur
					.getColumnIndex(UnitEntity.CREATEDDATE)));
			return values;
		}
		return null;
	}
}